<?php

namespace app\api\model;

use app\common\service\Email;

class DownloadLog extends \app\common\model\DownloadLog
{
    public static function getOne($oauthId, $fileId)
    {
        return static::field('id, create_time')
            ->where(['oauth_id' => $oauthId, 'file_id' => $fileId])
            ->find();
    }

    /**
     * 发送邮件并添加下载记录
     * @param $oauthId
     * @param $fileId
     * @param $file
     * @param $email
     * @return bool
     */
    public static function download($oauthId, $fileId, $file, $email)
    {
        // 1.下载文件到本地
        $res = download_file($file);

        if ($res !== false && isset($res['filePath'])) {
            // 2.发送邮件
            $res = Email::send($email, $res['filePath']);

            if ($res['code'] == 0) {
                // 3.添加下载记录
                static::create([
                    'oauth_id' => $oauthId,
                    'email' => $email,
                    'file_id' => $fileId,
                ]);
                return true;
            }

        }
        return false;
    }
}